//
//  DMComplianceManager.m
//  DualMediationSDK
//
//  合规管理器实现 - 重构版本
//

#import "DMComplianceManager.h"
#import "DMAdConfig.h"
#import "DMComplianceDelegate.h"
#import "../Models/DMUserConsent.h"
#import "../AD/Common/DMAdDelegate.h"
#import "../Utils/Device/IMDeviceUtils.h"
#import "../Utils/Logger/IMLogUtils.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
 #if __has_include(<UserMessagingPlatform/UserMessagingPlatform.h>)
  #define DM_HAS_UMP 1
  #import <UserMessagingPlatform/UserMessagingPlatform.h>
 #else
  #define DM_HAS_UMP 0
 #endif
#else
 #define DM_HAS_UMP 0
#endif

// 为了在非 iOS 平台上避免类型未声明错误，添加前向声明
@class UIViewController;

#if TARGET_OS_IPHONE
    #import <UIKit/UIKit.h>
#else
    #import <AppKit/AppKit.h>
#endif

// 合规相关常量
static NSString * const kComplianceInitializedKey = @"DMComplianceInitialized";

@interface DMComplianceManager ()

@property (nonatomic, strong) DMUserConsent *currentConsent;
@property (nonatomic, strong) dispatch_queue_t complianceQueue;
@property (nonatomic, strong) DMAdConfig *adConfig;
@property (nonatomic, assign, readwrite) BOOL isInitialized;

// 私有方法声明
- (void)requestUserConsentsWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion;
- (void)requestUMPConsentWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion;
- (void)requestCCPAConsentWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion;
- (void)completeInitialization;
- (void)loadStoredConsent;
- (void)saveConsent;
- (void)trackComplianceEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters;
- (void)logComplianceResults;

// 新增：delegate回调方法
- (void)notifyDelegateOnMainQueue:(void(^)(void))block;
- (DMComplianceResult *)buildCurrentComplianceStatus;

@end

@implementation DMComplianceManager

+ (instancetype)sharedManager {
    static DMComplianceManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMComplianceManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _complianceQueue = dispatch_queue_create("com.dualmediation.compliance.queue", DISPATCH_QUEUE_SERIAL);
        _currentConsent = [[DMUserConsent alloc] init];
        _adConfig = [DMAdConfig sharedConfig];
        _isInitialized = NO;
        [IMLogUtils info:IMLogTagSDKInit format:@"DMComplianceManager initialized"];
        [self loadStoredConsent];
    }
    return self;
}

#pragma mark - 对外公开的唯一方法

/**
 * 初始化合规管理并请求所有必要权限
 * 这是唯一的对外接口方法，会依次处理UMP、ATT等所有合规要求
 */
- (void)initializeComplianceWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagGeneral format:@"=== Starting compliance initialization ==="];
    [self trackComplianceEvent:@"compliance_flow_start" withParameters:nil];
    
    // 通知delegate开始合规检查
    [self notifyDelegateOnMainQueue:^{
        if ([self.delegate respondsToSelector:@selector(dmComplianceManagerDidStartComplianceCheck:)]) {
            [self.delegate dmComplianceManagerDidStartComplianceCheck:self];
        }
    }];
    
    // 检查是否已经初始化
    if (self.isInitialized) {
        [IMLogUtils info:IMLogTagGeneral format:@"Compliance already initialized"];
        
        // 通知delegate合规检查完成
        [self notifyDelegateOnMainQueue:^{
            if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didCompleteComplianceCheck:)]) {
                [self.delegate dmComplianceManager:self didCompleteComplianceCheck:[self buildCurrentComplianceStatus]];
            }
        }];
        
        if (completion) completion(YES, nil);
        return;
    }
    
    dispatch_async(_complianceQueue, ^{
        [self requestUserConsentsWithCompletion:^(BOOL success, NSError *error) {
            if (success) {
                self.isInitialized = YES;
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kComplianceInitializedKey];
                [IMLogUtils info:IMLogTagGeneral format:@"=== Compliance initialization completed successfully ==="];
                [self trackComplianceEvent:@"compliance_flow_complete" withParameters:@{@"success": @(YES)}];
                [self completeInitialization];
            } else {
                [IMLogUtils error:IMLogTagGeneral format:@"=== Compliance initialization failed: %@ ===", error.localizedDescription];
                [self trackComplianceEvent:@"compliance_flow_complete" withParameters:@{@"success": @(NO), @"error": error.localizedDescription ?: @"Unknown error"}];
            }
            
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(success, error);
                });
            }
        }];
    });
}

#pragma mark - 私有实现方法

- (void)requestUserConsentsWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagGeneral format:@"Starting comprehensive user consent requests"];
    
    // 按顺序处理：UMP -> CCPA (ATT已移至DMLifecycleManager)
    [self requestUMPConsentWithCompletion:^(BOOL umpSuccess, NSError *umpError) {
        [IMLogUtils info:IMLogTagGeneral format:@"📋 UMP consent completed: %@ %@", 
         umpSuccess ? @"✅ SUCCESS" : @"❌ FAILED", 
         umpError ? [NSString stringWithFormat:@"(%@)", umpError.localizedDescription] : @""];
        
        [self requestCCPAConsentWithCompletion:^(BOOL ccpaSuccess, NSError *ccpaError) {
            [IMLogUtils info:IMLogTagGeneral format:@"🏛️ CCPA consent completed: %@ %@", 
             ccpaSuccess ? @"✅ SUCCESS" : @"❌ FAILED",
             ccpaError ? [NSString stringWithFormat:@"(%@)", ccpaError.localizedDescription] : @""];
            
            // 记录所有合规结果
            [self logComplianceResults];
            
            // 整体成功判断：UMP和CCPA成功即可
            BOOL overallSuccess = umpSuccess && ccpaSuccess;
            NSError *finalError = umpError ?: ccpaError;
            
            [IMLogUtils info:IMLogTagGeneral format:@"🎯 All consent requests completed - Overall: %@", 
             overallSuccess ? @"✅ SUCCESS" : @"❌ FAILED"];
            
            // 通知delegate最终结果
            [self notifyDelegateOnMainQueue:^{
                if (overallSuccess) {
                    if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didCompleteComplianceCheck:)]) {
                        [self.delegate dmComplianceManager:self didCompleteComplianceCheck:[self buildCurrentComplianceStatus]];
                    }
                } else {
                    if ([self.delegate respondsToSelector:@selector(dmComplianceManager:didFailComplianceCheck:)]) {
                        [self.delegate dmComplianceManager:self didFailComplianceCheck:finalError];
                    }
                }
            }];
            
            completion(overallSuccess, finalError);
        }];
    }];
}

- (void)requestUMPConsentWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagGeneral format:@"--- Starting UMP Consent Request ---"];
    [self trackComplianceEvent:@"ump_request_start" withParameters:nil];

#if DM_HAS_UMP
    dispatch_async(dispatch_get_main_queue(), ^{
        UMPRequestParameters *params = [[UMPRequestParameters alloc] init];
        // 仅在调试模式下使用UMP调试地理设置，避免在非GDPR地区强制触发表单
        if (self.adConfig.isDebugMode) {
            UMPDebugSettings *debug = [[UMPDebugSettings alloc] init];
            // 默认不强制指定地区；如需测试可在外部赋值
            // debug.geography = UMPDebugGeographyEEA;
            params.debugSettings = debug;
        }

        [UMPConsentInformation.sharedInstance requestConsentInfoUpdateWithParameters:params
                                                                 completionHandler:^(NSError * _Nullable updateError) {
            if (updateError) {
                [IMLogUtils warning:IMLogTagGeneral format:@"UMP requestConsentInfoUpdate error: %@", updateError.localizedDescription];
                self.currentConsent.umpStatus = DMConsentStatusUnknown;
                [self saveConsent];
                // 对可恢复的网络错误（超时/离线等）不阻断SDK初始化
                BOOL isTransientNetworkError = [updateError.domain isEqualToString:NSURLErrorDomain] && (
                    updateError.code == NSURLErrorTimedOut ||
                    updateError.code == NSURLErrorNotConnectedToInternet ||
                    updateError.code == NSURLErrorCannotFindHost ||
                    updateError.code == NSURLErrorCannotConnectToHost ||
                    updateError.code == NSURLErrorNetworkConnectionLost
                );
                [self trackComplianceEvent:@"ump_request_complete" withParameters:@{ @"success": isTransientNetworkError ? @(YES) : @(NO), @"error": updateError.localizedDescription ?: @"unknown", @"tolerated": @(isTransientNetworkError) }];
                if (completion) completion(isTransientNetworkError, isTransientNetworkError ? nil : updateError);
                return;
            }

            UMPConsentStatus status = UMPConsentInformation.sharedInstance.consentStatus;
            [IMLogUtils info:IMLogTagGeneral format:@"UMP consentStatus after update: %ld", (long)status];

            void (^finishWithStatus)(DMConsentStatus) = ^(DMConsentStatus dmStatus){
                self.currentConsent.umpStatus = dmStatus;
                [self saveConsent];
                [self trackComplianceEvent:@"ump_request_complete" withParameters:@{ @"success": @(YES), @"status": @(dmStatus) }];
                if (completion) completion(YES, nil);
            };

            if (status == UMPConsentStatusRequired) {
                [IMLogUtils info:IMLogTagGeneral format:@"UMP status Required, loading consent form..."];
                [UMPConsentForm loadWithCompletionHandler:^(UMPConsentForm * _Nullable form, NSError * _Nullable loadError) {
                    if (loadError) {
                        [IMLogUtils warning:IMLogTagGeneral format:@"UMP load form error: %@", loadError.localizedDescription];
                        self.currentConsent.umpStatus = DMConsentStatusUnknown;
                        [self saveConsent];
                        BOOL isTransientNetworkError = [loadError.domain isEqualToString:NSURLErrorDomain] && (
                            loadError.code == NSURLErrorTimedOut ||
                            loadError.code == NSURLErrorNotConnectedToInternet ||
                            loadError.code == NSURLErrorCannotFindHost ||
                            loadError.code == NSURLErrorCannotConnectToHost ||
                            loadError.code == NSURLErrorNetworkConnectionLost
                        );
                        if (completion) completion(isTransientNetworkError, isTransientNetworkError ? nil : loadError);
                        return;
                    }

                    UIViewController *rootVC = [self getRootViewController];
                    if (!rootVC) {
                        NSError *noVCError = [NSError errorWithDomain:@"DMComplianceManager" code:1001 userInfo:@{ NSLocalizedDescriptionKey: @"No root view controller to present UMP form" }];
                        [IMLogUtils warning:IMLogTagGeneral format:@"%@", noVCError.localizedDescription];
                        // 在无法展示表单的场景下，不阻断初始化（标记为未知）
                        if (completion) completion(YES, nil);
                        return;
                    }

                    [form presentFromViewController:rootVC completionHandler:^(NSError * _Nullable presentError) {
                        if (presentError) {
                            [IMLogUtils warning:IMLogTagGeneral format:@"UMP present form error: %@", presentError.localizedDescription];
                            self.currentConsent.umpStatus = DMConsentStatusUnknown;
                            [self saveConsent];
                            BOOL isTransientNetworkError = [presentError.domain isEqualToString:NSURLErrorDomain] && (
                                presentError.code == NSURLErrorTimedOut ||
                                presentError.code == NSURLErrorNotConnectedToInternet ||
                                presentError.code == NSURLErrorCannotFindHost ||
                                presentError.code == NSURLErrorCannotConnectToHost ||
                                presentError.code == NSURLErrorNetworkConnectionLost
                            );
                            if (completion) completion(isTransientNetworkError, isTransientNetworkError ? nil : presentError);
                            return;
                        }

                        // 表单关闭后状态已更新
                        UMPConsentStatus newStatus = UMPConsentInformation.sharedInstance.consentStatus;
                        [IMLogUtils info:IMLogTagGeneral format:@"UMP consentStatus after form: %ld", (long)newStatus];
                        switch (newStatus) {
                            case UMPConsentStatusObtained: finishWithStatus(DMConsentStatusGranted); break;
                            case UMPConsentStatusNotRequired: finishWithStatus(DMConsentStatusNotRequired); break;
                            case UMPConsentStatusRequired: finishWithStatus(DMConsentStatusDenied); break;
                            default: finishWithStatus(DMConsentStatusUnknown); break;
                        }
                    }];
                }];
            } else if (status == UMPConsentStatusObtained) {
                finishWithStatus(DMConsentStatusGranted);
            } else if (status == UMPConsentStatusNotRequired) {
                finishWithStatus(DMConsentStatusNotRequired);
            } else {
                finishWithStatus(DMConsentStatusUnknown);
            }
        }];
    });
#else
    // 平台/环境不支持 UMP，标记为不需要或未知
    #if TARGET_OS_IPHONE
        self.currentConsent.umpStatus = DMConsentStatusUnknown;
    #else
        self.currentConsent.umpStatus = DMConsentStatusNotRequired;
    #endif
    [self saveConsent];
    [self trackComplianceEvent:@"ump_request_complete" withParameters:@{ @"success": @(YES), @"skipped": @(YES) }];
    if (completion) completion(YES, nil);
#endif
}



- (void)completeInitialization {
    [IMLogUtils info:IMLogTagGeneral format:@"Completing compliance initialization"];
    
    // 触发广告平台初始化或其他后续操作
    // 可以在这里添加通知或回调，告知其他组件合规初始化已完成
    
    [IMLogUtils info:IMLogTagGeneral format:@"Compliance initialization finalized"];
}

#pragma mark - 存储和恢复

- (void)loadStoredConsent {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    self.isInitialized = [defaults boolForKey:kComplianceInitializedKey];
    
    // 加载GDPR状态
    self.currentConsent.gdprApplies = [defaults boolForKey:@"dm_gdpr_applies"];
    self.currentConsent.gdprConsentString = [defaults stringForKey:@"dm_gdpr_consent"];
    
    NSDate *gdprDate = [defaults objectForKey:@"dm_gdpr_date"];
    if (gdprDate) {
        self.currentConsent.gdprConsentDate = gdprDate;
    }
    
    // 加载CCPA状态
    self.currentConsent.ccpaApplies = [defaults boolForKey:@"dm_ccpa_applies"];
    self.currentConsent.ccpaStatus = [defaults integerForKey:@"dm_ccpa_status"];
    
    NSDate *ccpaDate = [defaults objectForKey:@"dm_ccpa_optout_date"];
    if (ccpaDate) {
        self.currentConsent.ccpaOptOutDate = ccpaDate;
    }
    
    // 加载UMP状态
    self.currentConsent.umpStatus = [defaults integerForKey:@"dm_ump_status"];
    
    [IMLogUtils debug:IMLogTagGeneral format:@"Loaded stored consent - Initialized: %@, GDPR: %@, CCPA: %@, UMP: %ld", 
     self.isInitialized ? @"YES" : @"NO", 
     self.currentConsent.gdprConsentString ?: @"none",
     self.currentConsent.ccpaApplies ? @"applies" : @"not_applies",
     (long)self.currentConsent.umpStatus];
}

- (void)saveConsent {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    // 保存GDPR状态
    [defaults setBool:self.currentConsent.gdprApplies forKey:@"dm_gdpr_applies"];
    
    if (self.currentConsent.gdprConsentString) {
        [defaults setObject:self.currentConsent.gdprConsentString forKey:@"dm_gdpr_consent"];
    }
    if (self.currentConsent.gdprConsentDate) {
        [defaults setObject:self.currentConsent.gdprConsentDate forKey:@"dm_gdpr_date"];
    }
    
    // 保存CCPA状态
    [defaults setBool:self.currentConsent.ccpaApplies forKey:@"dm_ccpa_applies"];
    [defaults setInteger:self.currentConsent.ccpaStatus forKey:@"dm_ccpa_status"];
    if (self.currentConsent.ccpaOptOutDate) {
        [defaults setObject:self.currentConsent.ccpaOptOutDate forKey:@"dm_ccpa_optout_date"];
    }
    
    // 保存UMP状态
    [defaults setInteger:self.currentConsent.umpStatus forKey:@"dm_ump_status"];
    
    // 不强制同步写入，系统会在适当时机落盘，避免阻塞
    
    [IMLogUtils debug:IMLogTagGeneral format:@"All consent data saved to persistent storage"];
}

#pragma mark - CCPA 合规处理

- (void)requestCCPAConsentWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
    [IMLogUtils info:IMLogTagGeneral format:@"--- Starting CCPA Consent Request ---"];
    [self trackComplianceEvent:@"ccpa_request_start" withParameters:nil];
    
    // 检查是否在CCPA管辖区域
    if (![self isInCCPAJurisdiction]) {
        [IMLogUtils info:IMLogTagGeneral format:@"Not in CCPA jurisdiction, skipping CCPA consent"];
        self.currentConsent.ccpaApplies = NO;
        self.currentConsent.ccpaStatus = DMConsentStatusNotRequired;
        [self saveConsent];
        [self trackComplianceEvent:@"ccpa_request_complete" withParameters:@{@"success": @(YES), @"skipped": @(YES), @"reason": @"not_in_jurisdiction"}];
        completion(YES, nil);
        return;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"In CCPA jurisdiction, checking stored consent"];
    
    // 检查是否已有存储的CCPA选择
    NSString *storedCCPAChoice = [[NSUserDefaults standardUserDefaults] stringForKey:@"dm_ccpa_choice"];
    if (storedCCPAChoice) {
        [IMLogUtils info:IMLogTagGeneral format:@"Found stored CCPA choice: %@", storedCCPAChoice];
        [self applyCCPAChoice:storedCCPAChoice];
        [self trackComplianceEvent:@"ccpa_request_complete" withParameters:@{@"success": @(YES), @"skipped": @(YES), @"reason": @"choice_stored", @"choice": storedCCPAChoice}];
        completion(YES, nil);
        return;
    }
    
    // 显示CCPA隐私选择对话框
    [self showCCPAPrivacyDialogWithCompletion:completion];
}

- (BOOL)isInCCPAJurisdiction {
    // 参考 hegui.h 中的州/省判断逻辑
    NSArray *ccpaStates = @[
        @"加利福尼亚州",
        @"科罗拉多州", 
        @"康涅狄格州",
        @"蒙大拿州",
        @"得克萨斯州",
        @"德克萨斯州",
        @"犹他州",
        @"弗吉尼亚州"
    ];
    
    // 如果是调试模式，添加更多测试州
    if (self.adConfig.isDebugMode) {
        ccpaStates = [ccpaStates arrayByAddingObjectsFromArray:@[
            @"纽约州",
            @"华盛顿州",
            @"California",
            @"Colorado",
            @"Connecticut",
            @"Montana",
            @"Texas",
            @"Utah",
            @"Virginia",
            @"New York",
            @"Washington"
        ]];
    }
    
    // 获取用户地理位置信息（这里可以从设备信息或网络请求获取）。
    // 未知时不默认命中CCPA区域，避免误触发弹窗。
    NSString *userState = self.currentConsent.stateCode;
    if (userState == nil || userState.length == 0) {
        [IMLogUtils debug:IMLogTagGeneral format:@"CCPA jurisdiction check - State: unknown, In jurisdiction: NO"];
        return NO;
    }
    BOOL inJurisdiction = [ccpaStates containsObject:userState];
    [IMLogUtils debug:IMLogTagGeneral format:@"CCPA jurisdiction check - State: %@, In jurisdiction: %@", 
     userState, inJurisdiction ? @"YES" : @"NO"];
    
    return inJurisdiction;
}

- (void)showCCPAPrivacyDialogWithCompletion:(void(^)(BOOL success, NSError * _Nullable error))completion {
#if TARGET_OS_IPHONE
    dispatch_async(dispatch_get_main_queue(), ^{
        // 获取根视图控制器
        UIViewController *rootViewController = [self getRootViewController];
        if (!rootViewController) {
            NSError *error = [NSError errorWithDomain:@"DMComplianceManager" 
                                                 code:1002 
                                             userInfo:@{NSLocalizedDescriptionKey: @"No root view controller for CCPA dialog"}];
            completion(NO, error);
            return;
        }
        
        // 创建CCPA隐私选择对话框（参考 hegui.h 的实现）
        UIAlertController *alertController = [UIAlertController 
            alertControllerWithTitle:@"Privacy Preferences" 
            message:@"\n  We need your consent to process your personal information in order to comply with relevant U.S. state privacy laws, such as the California Privacy Rights Act (CPRA), Virginia Consumer Data Protection Act (VCDPA), Connecticut Personal Information Protection Act (CT DPA), Colorado Privacy Act (CPA), and Utah Consumer Privacy Act (UCPC). You have the right to choose whether to allow us to sell or share your personal information. We do not sell your personal information to show you ads. If your information is sold or has been sold by other companies, you may still see interest-based ads." 
            preferredStyle:UIAlertControllerStyleAlert];
        
        // "Sell or share" 选项
        UIAlertAction *sellAction = [UIAlertAction 
            actionWithTitle:@"Sell or share" 
            style:UIAlertActionStyleDefault 
            handler:^(UIAlertAction *action) {
                [IMLogUtils info:IMLogTagGeneral format:@"User chose: Sell or share"];
                [self trackComplianceEvent:@"ccpa_dialog_action" withParameters:@{@"choice": @"sell"}];
                [self applyCCPAChoice:@"sell"];
                [[NSUserDefaults standardUserDefaults] setObject:@"sell" forKey:@"dm_ccpa_choice"];
                [self trackComplianceEvent:@"ccpa_request_complete" withParameters:@{@"success": @(YES)}];
                completion(YES, nil);
            }];
        
        // "Do not sell or share" 选项
        UIAlertAction *doNotSellAction = [UIAlertAction 
            actionWithTitle:@"Do not sell or share" 
            style:UIAlertActionStyleCancel 
            handler:^(UIAlertAction *action) {
                [IMLogUtils info:IMLogTagGeneral format:@"User chose: Do not sell or share"];
                [self trackComplianceEvent:@"ccpa_dialog_action" withParameters:@{@"choice": @"not_sell"}];
                [self applyCCPAChoice:@"not_sell"];
                [[NSUserDefaults standardUserDefaults] setObject:@"not_sell" forKey:@"dm_ccpa_choice"];
                [self trackComplianceEvent:@"ccpa_request_complete" withParameters:@{@"success": @(YES)}];
                completion(YES, nil);
            }];
        
        [alertController addAction:sellAction];
        [alertController addAction:doNotSellAction];
        
        [rootViewController presentViewController:alertController animated:YES completion:nil];
    });
#else
    // macOS 平台下的 CCPA 处理（如果需要的话）
    [IMLogUtils info:IMLogTagGeneral format:@"CCPA dialog not supported on macOS, using default consent"];
    [self applyCCPAChoice:@"not_sell"]; // 默认不允许销售/分享
    completion(YES, nil);
#endif
}

- (void)applyCCPAChoice:(NSString *)choice {
    self.currentConsent.ccpaApplies = YES;
    
    if ([choice isEqualToString:@"not_sell"]) {
        self.currentConsent.ccpaStatus = DMConsentStatusDenied;
        self.currentConsent.ccpaOptOutDate = [NSDate date];
        [IMLogUtils info:IMLogTagGeneral format:@"CCPA: User opted out of data selling/sharing"];
    } else {
        self.currentConsent.ccpaStatus = DMConsentStatusGranted;
        [IMLogUtils info:IMLogTagGeneral format:@"CCPA: User consented to data selling/sharing"];
    }
    
    [self saveConsent];
}

- (UIViewController *)getRootViewController {
#if TARGET_OS_IPHONE
    UIViewController *rootViewController = nil;
    if (@available(iOS 15.0, *)) {
        UIWindowScene *scene = (UIWindowScene *)[UIApplication sharedApplication].connectedScenes.anyObject;
        rootViewController = scene.windows.firstObject.rootViewController;
    } else {
        rootViewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
    }
    return rootViewController;
#else
    return nil; // macOS 平台不支持
#endif
}

#pragma mark - 合规结果记录

- (void)logComplianceResults {
    [IMLogUtils info:IMLogTagGeneral format:@"=== Compliance Results Summary ==="];
    [IMLogUtils info:IMLogTagGeneral format:@"UMP Status: %ld", (long)self.currentConsent.umpStatus];
    [IMLogUtils info:IMLogTagGeneral format:@"GDPR Applies: %@, Status: %ld", 
     self.currentConsent.gdprApplies ? @"YES" : @"NO", (long)self.currentConsent.gdprStatus];
    [IMLogUtils info:IMLogTagGeneral format:@"CCPA Applies: %@, Status: %ld", 
     self.currentConsent.ccpaApplies ? @"YES" : @"NO", (long)self.currentConsent.ccpaStatus];
    [IMLogUtils info:IMLogTagGeneral format:@"================================="];
}

- (BOOL)isInitialized {
    return _isInitialized;
}

- (DMUserConsent *)getCurrentUserConsent {
    return [self.currentConsent copy];
}

- (DMComplianceStatus *)getCurrentComplianceStatus {
    DMComplianceResult *result = [self buildCurrentComplianceStatus];
    return result.complianceStatus;
}

- (void)trackComplianceEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters {
    NSMutableDictionary *eventData = [NSMutableDictionary dictionary];
    [eventData setObject:eventName forKey:@"event_name"];
    if (parameters) {
        [eventData addEntriesFromDictionary:parameters];
    }
    
    // 使用IMLogUtils模拟事件上报，实际项目中应替换为真实的分析SDK
    // 在第154行，将 IMLogTagAnalytics 替换为 IMLogTagGeneral
    [IMLogUtils info:IMLogTagGeneral format:@"Compliance Event: %@", eventData];
}

#pragma mark - Delegate Helper Methods

- (void)notifyDelegateOnMainQueue:(void(^)(void))block {
    if (block) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
    }
}

- (DMComplianceResult *)buildCurrentComplianceStatus {
    DMComplianceResult *result = [[DMComplianceResult alloc] init];
    result.isCompliant = self.isInitialized;
    result.userConsent = [self getCurrentUserConsent];
    
    // 构建合规状态
    DMComplianceStatus *status = [[DMComplianceStatus alloc] init];
    status.gdprApplies = self.currentConsent.gdprApplies;
    status.gdprConsent = (self.currentConsent.gdprStatus == DMConsentStatusGranted);
    status.ccpaApplies = self.currentConsent.ccpaApplies;
    status.ccpaOptOut = (self.currentConsent.ccpaStatus == DMConsentStatusDenied);
    status.region = @"US"; // 可以根据实际地理位置设置
    
    result.complianceStatus = status;
    result.error = nil;
    
    return result;
}

@end
